package com.dushuren.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dushuren.project.common.ErrorCode;
import com.dushuren.project.exception.BusinessException;
import com.dushuren.project.mapper.UserTeamMapper;
import com.dushuren.project.model.entity.UserTeam;
import com.dushuren.project.model.vo.UserTeamVo;
import com.dushuren.project.service.UserTeamService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author qieqie
* @description 针对表【user_team(队伍成员关系管理)】的数据库操作Service实现
* @createDate 2022-10-17 12:35:33
*/
@Service
public class UserTeamServiceImpl extends ServiceImpl<UserTeamMapper, UserTeam>
    implements UserTeamService {

  @Resource
  UserTeamMapper userTeamMapper;


  /***
   * 获取当前加入队伍的数量
   * @param userId
   * @return
   */
  @Override
  public Long QueryUserTeam(Long userId) {
	QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
	queryWrapper.select("id");
	queryWrapper.eq("userId",userId);
	Long count = userTeamMapper.selectCount(queryWrapper);
	if (count >= 5) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR, "加入的队伍已满");
	}
	return count;
  }

  @Override
  public Long QueryTeamNum(Long teamId) {
	QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
	queryWrapper.select("id");
	queryWrapper.eq("teamId",teamId);
	return userTeamMapper.selectCount(queryWrapper);
  }

  @Override
  public Long QueryTeamNum(Long teamId, Long userId) {
	QueryWrapper<UserTeam> queryWrapperUserTeam = new QueryWrapper<>();
	queryWrapperUserTeam.select("id");
	queryWrapperUserTeam.eq("teamId", teamId);
	queryWrapperUserTeam.eq("userId", userId);
	Long count = userTeamMapper.selectCount(queryWrapperUserTeam);
	return count;
  }

  /***
   * 查询当前队伍中是否存在者成员，存在则返回
   * @param teamId
   * @param userId
   * @return
   */
  @Override
  public UserTeamVo isIdTeamExist(Long teamId, Long userId) {
	QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
	queryWrapper.select("id", "userId", "teamId", "joinTeam");
	queryWrapper.eq("teamId", teamId);
	queryWrapper.eq("userId", userId);
	UserTeam userTeam = userTeamMapper.selectOne(queryWrapper);
	UserTeamVo teamVo = new UserTeamVo();
	BeanUtils.copyProperties(userTeam,teamVo);
	if (teamVo.getId() <= 0) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR);
	}
	return teamVo;
  }
}




